#include "transferFile.h"

int transferFile(int netfd, char *fileName) {
    train_t train;

    //先发文件名,再发送文件大小(打印进度条),最后循环发送文件内容
    //组装文件名小火车
    train.len = strlen(fileName);
    memcpy(train.data, fileName, train.len);
    send(netfd, &train, sizeof(train.len) + train.len, MSG_NOSIGNAL);
    
    //发送文件大小
    int fd = open(fileName, O_RDWR);
    if(fd == -1) {
        error(1, errno, "open");
    }
    //获取文件大小
    struct stat fileStat; 
    fstat(fd, &fileStat);

    //组装文件大小火车
    train.len = sizeof(off_t);
    memcpy(train.data, &fileStat.st_size, train.len);
    send(netfd, &train, sizeof(train.len) + train.len, MSG_NOSIGNAL);

    //发送文件方进度条
    off_t cursize = 0;
    off_t lastsize = 0;
    off_t slice = fileStat.st_size / 100;

    //循环发送文件内容
    while(1) {
        ssize_t sret = read(fd, train.data, sizeof(train.data));
        train.len = sret;
        ssize_t sret1 = send(netfd, &train, sizeof(train.len) + train.len, MSG_NOSIGNAL);
        cursize += train.len;
        //发送一个空数据包,表示循环结束 || send异常
        if(sret == 0 || sret1 == -1) {
            break;
        }
        //控制进度条的打印速度
        if(cursize - lastsize > slice) {
            printf("transfer progress bar:%5.2f%%\r", cursize * 100.0 / fileStat.st_size);
            fflush(stdout);
            lastsize = cursize;
        }
    }
    printf("transfer progress bar:100.00%%\n");
    return 0;
}
